﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Text.RegularExpressions;

namespace DFGK_WMS.Repository
{
    public class DepartmentRepository : BaseRepository<TDepartment>, IDepartmentRepository
    {
        public DepartmentRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }


        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public List<Menuitem> GetDepartment()
        {
            var list = Context.TDepartments.AsQueryable();
            list = list.OrderBy(x => x.ParentId);
            var mmlist = list.FirstOrDefault();
            return GetMenuitems(list.ToList(), (int)mmlist.ParentId);
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<Menuitem> GetMenuitems(List<TDepartment> list, int pid)
        {
            return list.Where(x => x.ParentId == pid).Select(x => new Menuitem
            {
                value = x.Id,
                label = x.DepartmentName,
                parent = x.ParentId,
                children = GetMenuitems(list, x.Id)
            }).ToList();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddDepartment(TDepartment m)
        {
            try
            {
                var dictype = Context.TDictItems.AsNoTracking().FirstOrDefault(x => x.Id == m.DepartmentTypeId);
                if (dictype != null)
                {
                    m.DepartmentTypeId = dictype.Id;
                    m.DepartmentTypeName = dictype.ItemName;
                }
                var obj = Context.TDepartments.AsNoTracking().Where(x => x.DepartmentCode.Contains(m.DepartmentName)).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                if (obj != null)
                {
                    string pattern = @"\d+";
                    MatchCollection matches = Regex.Matches(obj.DepartmentCode, pattern);
                    string value = matches[matches.Count - 1].Value;
                    int values = Convert.ToInt32(value);
                    values++;
                    m.DepartmentCode = m.DepartmentName + values.ToString("D3");
                    Context.TDepartments.Add(m);
                    return Context.SaveChanges() > 0;
                }
                int i = 1;
                m.DepartmentCode = m.DepartmentName + i.ToString("D3");
                Context.TDepartments.Add(m);
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdateDepartment(TDepartment m)
        {
            try
            {
                var dictype = Context.TDictItems.AsNoTracking().FirstOrDefault(x => x.Id == m.DepartmentTypeId);
                if (dictype != null)
                {
                    m.DepartmentTypeId = dictype.Id;
                    m.DepartmentTypeName = dictype.ItemName;
                }
                Context.TDepartments.Update(m);

                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DelDepartment(int ids)
        {

            try
            {
                var dep = Context.TDepartments.Find(ids);
                if (dep != null)
                {
                    Context.TDepartments.Remove(dep);
                }
                bool result = Context.SaveChanges() > 0;
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 部门分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TDepartment> GetDepartments(string name, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TDepartments.AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    list = list.Where(x => x.DepartmentName.Contains(name));
                }
                totalCount = list.Count();
                list = list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return list.ToList();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public TDepartment GetDepartment(int ids)
        {
            var dobj = Context.TDepartments.Find(ids);

            return dobj;
        }

        /// <summary>
        /// 查询部门单位类型
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TDictItem> GetTDepartmentDic()
        {
            int dicTypeId = 0;
            var dicType = Context.TDictTypes.Where(c => c.TypeCode == "bumen");
            var resList = new List<TDictItem>();
            if (dicType.Count() != 0)
            {
                dicTypeId = dicType.First().Id;
                foreach (var item in Context.TDictItems)
                {
                    if (item.TypeId == dicTypeId)
                        resList.Add(item);
                }
            }
            return resList;
        }

        /// <summary>
        /// 部门查询
        /// </summary>
        /// <returns></returns>
        public List<DepartmentSelectDto> GetDepartmentSelectList(int pageIndex, int pageSize, out int totaCount)
        {
            List<DepartmentSelectDto> dto = new List<DepartmentSelectDto>();
            List<DepartmentSelectDto> businessWarehouses = new List<DepartmentSelectDto>();
            List<DepartmentSelectDto> customerUnits = new List<DepartmentSelectDto>();
            List<DepartmentSelectDto> supplierUnits = new List<DepartmentSelectDto>();

            var departmentList = Context.TDepartments.AsQueryable();
            foreach (var department in departmentList)
            {
                DepartmentSelectDto dto2 = new DepartmentSelectDto();
                dto2.companyType = "业务仓库";
                dto2.companyName = department.DepartmentName;
                dto2.companyCode = department.DepartmentCode;
                businessWarehouses.Add(dto2);
            }

            var customerList = Context.TCustomers.AsQueryable();
            foreach (var item in customerList)
            {
                DepartmentSelectDto dto3 = new DepartmentSelectDto();
                dto3.companyType = "供出单位";
                dto3.companyName = item.Name;
                dto3.companyCode = item.Code;
                customerUnits.Add(dto3);
            }

            var supplierList = Context.TSuppliers.AsQueryable();
            foreach (var item in supplierList)
            {
                DepartmentSelectDto dto4 = new DepartmentSelectDto();
                dto4.companyType = "供入单位";
                dto4.companyName = item.Name;
                dto4.companyCode = item.Code;
                supplierUnits.Add(dto4);
            }
            dto.AddRange(businessWarehouses);
            dto.AddRange(customerUnits);
            dto.AddRange(supplierUnits);
            totaCount = dto.Count();

            return dto.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
    }
}
